<?php /** @noinspection ALL */

use App\Models\EduMentalHealth;
use App\Models\EduMentalHealthTeacher;
use App\Models\MentalHealth;
use App\Models\Region;
use App\Models\School;
use App\Models\SchoolLevel;
use GuzzleHttp\Client as BaseClient;
use GuzzleHttp\Client as Client;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use App\Models\FormValidation;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Jenson\BaseAdmin\Libraries\Helper as AdminHelper;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Exception;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

/**
 * 成功返回
 *
 * @param $data
 * @param int $code
 * @param string $msg
 * @return array
 */
function ret($data, int $code = 200, string $msg = '请求成功',$httpCode = 200): array
{
    header('Access-Control-Allow-Origin:*');
    header('Access-Control-Allow-Headers:Origin, X-Requested-With,  Content-Type, Cookie, Accept, appid, channel, access-token, auth-token');
    header('Access-Control-Allow-Methods:GET, POST, PATCH, PUT, OPTIONS');
    header('Access-Control-Allow-Credentials:false');
    header('Access-Control-Max-Age:3600');
    header('Content-Type:text/html;charset=utf-8');
    header('Content-type:application/json');
    if($httpCode == 403 ){
        header('HTTP/1.1 403 Forbidden');
        echo json_encode([
            'code' => $code,
            'result' => [
                'msg' => $data
            ]
        ]);
        exit;
    }
    # 正常执行
    echo json_encode([
        'code' => $code,
        'result' => $data,
        'msg' => $msg ?: ($data['msg'] ?? null),
    ]);
    exit;
}

/**
 * 错误返回
 *
 * @param $msg
 * @param int $code
 * @return array
 */
function retError($msg = '请求失败', int $code = 201): array
{
    if(is_string($msg)){
        $result = [
            'msg' => $msg
        ];
    }else{
        $result = $msg;
        $msg = $result['msg'];
    }
    return ret($result,$code,$msg);
}
/**
 * 返回信息
 *
 * @param int $code
 * @param $msg
 * @param $data
 * @return array
 */
function returnInfo(int $code = 1 , $msg = null , $data = null): array
{
    return [
        'code'=>$code,
        'msg'=>$msg,
        'data'=>$data
    ];
}
/**
 * @param $tel
 * @param false $onlyMob
 * @return array|void
 *
 * 手机号合法性验证
 */
function  VerifyMobile($tel, bool $onlyMob = false)
{
//    preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#',$tel);
    $isMob = "/^1[3-9]{1}[0-9]{9}$/";
    $isTel = "/^([0-9]{3,4}-)?[0-9]{7,8}$/";
    $special = '/^(4|8)00(-\d{3,4}){2}$/';//'/^(4|8)00(\d{4,8})$/';
    $data3 = substr($tel, 0, 3);
    $data2 = substr($tel, 0, 2);
    $msg = 'success';
    $msg_zh = '成功';
    $code = 1;
    if ($onlyMob) {# 只验证手机号，不验证座机和400|800的号码
        if (preg_match($isMob, $tel)) {
            if ($data2 == 14) {
                if (!in_array($data3, [147, 145])) {
                    # 只开放 147,145
                    $msg = $data3 . ' is not open!';
                    $msg_zh = $data3 . ' 号段暂未开放！';
                    $code = 0;
                    return [
                        'code' => $code,
                        'msg' => $msg,
                        'msg_zh' => $msg_zh
                    ];
                }
            } else if ($data2 == 16) {
                if (!in_array($data3, [165, 166, 167])) {
                    # 只开放 165,166,167
                    $msg = $data3 . ' is not open';
                    $msg_zh = $data3 . ' 号段暂未开放！';
                    $code = 0;
                    return [
                        'code' => $code,
                        'msg' => $msg,
                        'msg_zh' => $msg_zh
                    ];
                }
            } else if ($data2 == 17) {
                if (in_array($data3, [179, 174])) {
                    # 未开放 179,174
                    $msg = $data3 . ' is not open';
                    $msg_zh = $data3 . ' 号段暂未开放！';
                    $code = 0;
                    return [
                        'code' => $code,
                        'msg' => $msg,
                        'msg_zh' => $msg_zh
                    ];
                }
            } else if ($data2 == 19) {
                if (!in_array($data3, [199, 198])) {
                    # 只开放 199,198
                    $msg = $data3 . ' is not open';
                    $msg_zh = $data3 . ' 号段暂未开放！';
                    $code = 0;
                    return [
                        'code' => $code,
                        'msg' => $msg,
                        'msg_zh' => $msg_zh
                    ];
                }
            }
        } else {
            $msg = 'Invalid mobile phone number';
            $msg_zh = '手机号不合法！';
            $code = 0;
            return [
                'code' => $code,
                'msg' => $msg,
                'msg_zh' => $msg_zh
            ];
        }
        return [
            'code' => $code,
            'msg' => $msg,
            'msg_zh' => $msg_zh
        ];
    } else {# 手机、座机、以及400|800号码的验证
        if (preg_match($isMob, $tel)) {
            if ($data2 == 14) {
                if (!in_array($data3, [147, 145])) {
                    # 只开放 147,145
                    $msg = $data3 . ' is not open!';
                    $msg_zh = $data3 . ' 号段暂未开放！';
                    $code = 0;
                    return [
                        'code' => $code,
                        'msg' => $msg,
                        'msg_zh' => $msg_zh
                    ];
                }
            } else if ($data2 == 16) {
                if (!in_array($data3, [165, 166, 167])) {
                    # 只开放 165,166,167
                    $msg = $data3 . ' is not open';
                    $msg_zh = $data3 . ' 号段暂未开放！';
                    $code = 0;
                    return [
                        'code' => $code,
                        'msg' => $msg,
                        'msg_zh' => $msg_zh
                    ];
                }
            } else if ($data2 == 17) {
                if (in_array($data3, [179, 174])) {
                    # 未开放 179,174
                    $msg = $data3 . ' is not open';
                    $msg_zh = $data3 . ' 号段暂未开放！';
                    $code = 0;
                    return [
                        'code' => $code,
                        'msg' => $msg,
                        'msg_zh' => $msg_zh
                    ];
                }
            } else if ($data2 == 19) {
                if (!in_array($data3, [199, 198])) {
                    # 只开放 199,198
                    $msg = $data3 . ' is not open';
                    $msg_zh = $data3 . ' 号段暂未开放！';
                    $code = 0;
                    return [
                        'code' => $code,
                        'msg' => $msg,
                        'msg_zh' => $msg_zh
                    ];
                }
            }
        } else if (preg_match($special, $tel)) {
            return [
                'code' => $code,
                'msg' => $msg,
                'msg_zh' => $msg_zh
            ];
        } else if (preg_match($isTel, $tel)) {
            return [
                'code' => $code,
                'msg' => $msg,
                'msg_zh' => $msg_zh
            ];
        } else {
            $msg = 'Invalid mobile phone number,If it is a fixed telephone, it must be like (010-87876787 or 400-000-0000)!';
            $msg_zh = '手机号不合法,如果是固定电话, 必须类似以下号码 (010-87876787 或者 400-000-0000)！';
            $code = 0;

            return [
                'code' => $code,
                'msg' => $msg,
                'msg_zh' => $msg_zh
            ];
        }
        return [
            'code' => $code,
            'msg' => $msg,
            'msg_zh' => $msg_zh
        ];
    }
}


/**
 * GuzzleHttpGet
 *
 * @param $url
 * @return mixed
 * @throws \GuzzleHttp\Exception\GuzzleException
 */
function GuzzleHttpGet($url)
{
//    $client = new Client();
    $client = new Client([
        'verify'=>false,#测试环境不做验证
    ]);
    $response = $client->request('GET', $url);
    $data = $response->getBody()->getContents();
    return json_decode($data, true);
}

/**
 * GuzzleHttpPost
 *
 * @param $url
 * @param $form_params
 * @return mixed
 * @throws \GuzzleHttp\Exception\GuzzleException
 */
function GuzzleHttpPost($url,$form_params)
{
//    $client = new Client();
    $client = new Client([
        'verify'=>false,#测试环境不做验证
    ]);
    $response = $client->request('post', $url,$form_params);
    $data = $response->getBody()->getContents();
    return json_decode($data,true);
}

/**
 * 删除数据
 *
 * @param $data
 * @param $op
 * @return array
 * @throws Throwable
 */
function DeleteData($data, $op): array
{
    DB::beginTransaction();
    try {
        $data->delete();
        # 记录管理员操作日志
        $params = [
            'admin_id' => session('uid'),
            'operation' => $op,
            'ip' => GetIPAddress(),
        ];
        # todo:添加操作日志
//        AdminHelper::addAdminLog($params);
        DB::commit();
        return ret('操作成功!');
    } catch (\Exception $e) {
        DB::rollBack();
        return retError($e->getMessage());
    }
}

/**
 * 表单验证
 *
 * @param $table
 * @param $request
 * @return array|void
 */
function FormVerifyOld($table, $request)
{
    $rules = array();
    $messages = array();
    $where = [
        'table' => $table,
//        'rule' => 'required'
    ];
    $data = FormValidation::query()->where($where)->oldest('sort')->get();
    if ($data) {
        foreach ($data as $key => $val) {
            $rules[$val['column']] = $val['rule'];
            $messages[$val['column'] . '.' . $val['rule']] = $val['message'];
        }
    }
    return ret($messages);
    $validator = Validator::make($request->all(), $rules, $messages);
    if ($validator->fails()) {
        $msg = array_values($validator->errors()->toArray())[0][0];
        return retError([
            'msg'=>$msg
        ]);
    }
    return true;
}

/**
 * 表单验证
 *
 * @param $table
 * @param $request
 * @return array|true|void
 */
function FormVerify($table, $request,$method = 'create')
{
    $where = [
        'table' => $table,
    ];
    $method_arr = [$method,'common'];
    $data = FormValidation::query()->where($where)->whereIn('method',$method_arr)->oldest('sort')->get();
    if ($data) {
        foreach ($data as $key => $val) {
            if($val['key'] == 'rule') {
                $rules[$val['column']] = $val['value'];
            }
            if($val['key'] == 'message') {
                $messages[$val['column'] . '.' . $val['value']] = $val['msg'];
            }
        }
        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->fails()) {
            $msg = array_values($validator->errors()->toArray())[0][0];
            return retError([
                'msg'=>$msg
            ]);
        }
        return ret([
            'msg'=>'ok'
        ]);
    }
}

/**
 * 更新数据时，数据唯一性验证
 *
 * @param $model
 * @param $id
 * @param $where
 * @return array|true
 */
function UpdateDataUniqueVerify($model,$id,$where)
{
    $data = $model->where('id','!=',$id)->where($where)->count();
    if($data > 0){
        return retError([
           'msg'=>'该数据已存在！',
        ]);
    }
    return true;
}
/**
 * @param $sex
 * @param false $color
 * @return string
 *
 * 性别
 */
function gender($sex, bool $color = false): string
{
    $gender = [
        0 => '未知',
        1 => '男',
        2 => '女',
    ];
    if ($color) {
        $gender = [
            0 => '<span style="color:blue;">未知</span>',
            1 => '<span style="color:green;">男</span>',
            2 => '<span style="color:red;">女</span>',
        ];
    }
    return $gender[$sex];
}

/**
 * @param array $files
 * @return array
 *
 * 文件解析
 */
function FileParsing(array $files): array
{
    $image_arr = array('jpg', 'jepg', 'png', 'git', 'bmp', 'tif', 'webp', 'psd', 'svg');
    $file_arr = array();
    foreach ($files as $val) {
        $arr = explode('/', $val);
        $file_name = end($arr);
        $arr_name = explode('.', $file_name);
        $file_ext = end($arr_name);
        $file_type = 'file';
        if (in_array($file_ext, $image_arr)) {
            $file_type = 'image';
        }
        $file_arr[] = [
            'file_path' => $val,
            'file_name' => $file_name,
            'file_real_path' => config('mbcore_mcore.base_url') . storage::url($val),
            'file_type' => $file_type
        ];
    }
    return $file_arr;
}

/**
 * 刷新JWT
 *
 * @param $token
 * @param $guard
 * @param $token_type
 * @param $hours
 * @return array
 */
function RespondWithToken($token,$guard = 'api',$token_type = 'bearer',$hours = 2)
{
    return [
        'access_token' => $token,
        'token_type' => $token_type,
        'expires_in' => auth($guard)->factory()->getTTL() * 60 * $hours
    ];
}

/**
 * @return array|false|mixed|string
 *
 * 获取真实IP
 */
function GetIPAddress(){
    if (isset($_SERVER)) {
        $realIp = $_SERVER['REMOTE_ADDR'];
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $realIp = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        if (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $realIp = $_SERVER['HTTP_CLIENT_IP'];
        }
    } else {
        $realIp = getenv("REMOTE_ADDR");
        if (getenv("HTTP_X_FORWARDED_FOR")) {
            $realIp = getenv( "HTTP_X_FORWARDED_FOR");
        }
        if (getenv("HTTP_CLIENT_IP")) {
            $realIp = getenv("HTTP_CLIENT_IP");
        }
    }
    return $realIp;
}

/**
 * 短信验证码验证
 *
 * @param $cacheKey
 * @return array|void
 */
function SmsCodeVetify($cacheKey){
    $captcha = Cache::get($cacheKey);
    #验证吗无效
    if(empty($captcha)) {
        return retError([
            'msg'=>'验证码已失效',
        ],201);
    }
    #验证码过期
    if($code != $captcha){
        return retError([
            'msg'=>'验证码错误',
        ],201);
    }
}

/**
 * Model Query
 *
 * @param $id
 * @param $model
 * @param $where
 * @return array|true
 */
function ModelQuery($id,$model,$where)
{
    if(!$id){
        return retError([
            'msg'=>'信息ID不能为空！'
        ]);
    }
    $data = $model->where($where)->count();
    if($data <=0){
        return retError([
            'msg'=>'数据不存在或已删除！'
        ]);
    }
    return true;
}

/**
 * @param int $num | 位数
 * @return string
 *
 * 生成随机码
 */
function ActivationCode($num = 6){
    $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $rand = $code[rand(0,25)]
        .strtoupper(dechex(date('m')))
        .date('d').substr(time(),-5)
        .substr(microtime(),2,5)
        .sprintf('d',rand(0,99));
    for(
        $a = md5( $rand, true ),
        $s = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        $code = '',
        $f = 0;
        $f < $num;
        $g = ord( $a[ $f ] ),
        $code .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ],
        $f++
    );
    return $code;
}
const available_status = '正常';
const unavailable_status = '禁用';
const waitavailable_status = '待审核';
/**
 * 获取状态值
 *
 * @param $status
 * @return string
 */
function getStatusValue($status){
    $status_value = unavailable_status;
    if($status == 1){
        $status_value = available_status;
    }
    if($status == 0){
        $status_value = waitavailable_status;
    }
    return $status_value;
}

/**
 * 获取状的HTML态值
 *
 * @param $status
 * @return string
 */
function getStatusHTMLValue($status){
    $status_value = '<span style="color:red;">unavailable_status</span>';
    if($status == 1){
        $status_value = '<span style="color:green;">available_status</span>';
    }
    return $status_value;
}

/**
 * 获取状值数组
 * @return string[]
 */
function getStatusArray(){
    return [
        0=>waitavailable_status,
        1=>available_status,
        2=>unavailable_status,
    ];
}

/**
 * @param $id_card
 * @return bool
 * 身份证验证
 */
function validateIDCard($id_card)
{

    $preg_card="/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/i";
    if(preg_match($preg_card,$id_card)){
        return true;
    }
    return false;
}


function pingyinFirstChar($sourcestr){

    $returnstr='';
    $i=0;
    $n=0;
    $str_length=strlen($sourcestr);//字符串的字节数
    dd($str_length);

    while ($i<=$str_length) {

        $temp_str=substr($sourcestr,$i,1);
        $ascnum=Ord($temp_str);//得到字符串中第$i位字符的ascii码

        if ($ascnum>=224){ //如果ASCII位高与224，
            $returnstr=$returnstr.getHanziInitial(substr($sourcestr,$i,3)); //根据UTF-8编码规范，将3个连续的字符计为单个字符
            $i=$i+3;//实际Byte计为3
        }else if($ascnum>=192){ //如果ASCII位高与192，
            $returnstr=$returnstr.getHanziInitial(substr($sourcestr,$i,2)); //根据UTF-8编码规范，将2个连续的字符计为单个字符
            $i=$i+2;//实际Byte计为2
        }else if($ascnum>=65 && $ascnum<=90){ //如果是大写字母，
            $returnstr=$returnstr.substr($sourcestr,$i,1);
            $i=$i+1;//实际的Byte数仍计1个
        }else{ //其他情况下，包括小写字母和半角标点符号，
            $returnstr=$returnstr.strtoupper(substr($sourcestr,$i,1)); //小写字母转换为大写
            $i=$i+1;//实际的Byte数计1个
        }
    }

    return $returnstr;
}

function getHanziInitial($s0){

    if(ord($s0) >= "1" and ord($s0) <= ord("z")){
        return strtoupper( substr($s0,0,1));
    }
    $s = iconv("UTF-8", "gb2312//IGNORE", $s0); // 不要转换成GB2312内没有的字符哦，^_^
    $asc = @ord($s{0}) * 256 + @ord($s{1})-65536;
    if($asc >= -20319 and $asc <= -20284)return "A";
    if($asc >= -20283 and $asc <= -19776)return "B";
    if($asc >= -19775 and $asc <= -19219)return "C";
    if($asc >= -19218 and $asc <= -18711)return "D";
    if($asc >= -18710 and $asc <= -18527)return "E";
    if($asc >= -18526 and $asc <= -18240)return "F";
    if($asc >= -18239 and $asc <= -17923)return "G";
    if($asc >= -17922 and $asc <= -17418)return "H";
    if($asc >= -17417 and $asc <= -16475)return "J";
    if($asc >= -16474 and $asc <= -16213)return "K";
    if($asc >= -16212 and $asc <= -15641)return "L";
    if($asc >= -15640 and $asc <= -15166)return "M";
    if($asc >= -15165 and $asc <= -14923)return "N";
    if($asc >= -14922 and $asc <= -14915)return "O";
    if($asc >= -14914 and $asc <= -14631)return "P";
    if($asc >= -14630 and $asc <= -14150)return "Q";
    if($asc >= -14149 and $asc <= -14091)return "R";
    if($asc >= -14090 and $asc <= -13319)return "S";
    if($asc >= -13318 and $asc <= -12839)return "T";
    if($asc >= -12838 and $asc <= -12557)return "W";
    if($asc >= -12556 and $asc <= -11848)return "X";
    if($asc >= -11847 and $asc <= -11056)return "Y";
    if($asc >= -11055 and $asc <= -10247)return "Z";
    return  substr($s0,0,1); // 返回原字符，不作转换。(标点、空格、繁体字都会直接返回)
}


function getImageUrl($str)
{
    if(empty($str)){
        return '';
    }

    $res = strpos($str, 'http');
    if($res === false ){
        //没找到

        return 'https://alumnus.biaoxufilm.com/'.$str;
    }else{
        //找到了

        return $str;
    }

}
